﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using MovieRental.SqlRepositoryLibrary.Helpers;
using MovieRental.Entities;


namespace MovieRental.SqlRepositoryLibrary.Converters
{
    public class LoanConverter : BaseConverter<LoanInfo, Guid>
    {
        protected override SqlEntityMapping SetUpMapping()
        {
            var mapping = new SqlEntityMapping("Loans", "LoanCartId");
            mapping.AddProperty("LoanCartId", "LoanCartId", SqlDbType.UniqueIdentifier);
            mapping.AddProperty("EditionId", "EditionId", SqlDbType.UniqueIdentifier);
            mapping.AddProperty("ReturnDate", "ReturnDate", SqlDbType.DateTime);
            mapping.AddProperty("PricePerDay", "PricePerDay", SqlDbType.Float);
            return mapping;
        }

        protected override void SetUpPropertyValues(LoanInfo entity)
        {
            SetProperty("LoanCartId", entity.LoanCartId);
            SetProperty("EditionId", entity.EditionId);
            SetProperty("ReturnDate", (entity.ReturnDate == DateTime.MinValue) ? (object) DBNull.Value : (object) entity.ReturnDate);
            SetProperty("PricePerDay", entity.PricePerDay);
        }

        public override LoanInfo ConvertFromDataReader(SqlDataReader reader)
        {
            var loan = new LoanInfo();
            loan.LoanCartId = (Guid)GetValueForProperty(reader, "LoanCartId");
            var editionId = GetValueForProperty(reader, "EditionId");
            loan.EditionId = (editionId == DBNull.Value) ? Guid.Empty : (Guid)editionId;
            var returnDate = GetValueForProperty(reader, "ReturnDate");
            loan.ReturnDate = returnDate == DBNull.Value ? DateTime.MinValue : (DateTime)returnDate;
            loan.PricePerDay = (double)GetValueForProperty(reader, "PricePerDay");
            return loan;
        }
    }
}
